const cheerio = require('cheerio');

function homepage(content) {
    const $ = cheerio.load(content);
    const liEles = $('li.top_nav li');
    var menu = [];
    for (let index = 0; index < liEles.length; index++) {
        const liEle = $(liEles[index]);
        var href = liEle.find('a').attr('href');
        if (href) {
            // href = href.replace('/class/', "/type/");
            href = href.replace('/item/', "/category/");
        }
        menu.push({
            title: liEle.text().trim(),
            href: liEle.find('a').attr('href'),
            hrefType: "videoList",
        });
    }
    const list = [];
    const divEles = $("div.vod_row div.pannel");
    for (let index = 0; index < divEles.length; index++) {
        const divEle = $(divEles[index]);
        const title1 = divEle.find('h2').text().trim();
        const liEles = divEle.find('ul.vodlist li');
        var children = [];
        for (let index = 0; index < liEles.length; index++) {
            const liEle = $(liEles[index]);
            const aEle = liEle.find('a');
            const href = aEle.attr('href');
            const title = aEle.attr('title');
            const imagePath = aEle.attr('data-original');
            const hint = aEle.text().trim();
            children.push({ title, href, hrefType: 'videoInfo', imagePath, hint, playHref: loadPlayHref(href) })
        }
        list.push({ title: title1, children, heref: '', hrefType: 'videoList', imagePath: '' });
    }
    return { menu, children: list };
}

function loadPlayHref(href) {
    return href.replace('/v/', '/p/').replace('.html', '-1-1.html');
}

function videoList(content) {
    const $ = cheerio.load(content);
    const ulEles = $('div.wrapper_fl ul.screen_list');
    const menu = [];
    for (let index = 0; index < ulEles.length; index++) {
        const ulEle = $(ulEles[index]);
        const liEles = ulEle.find('li');
        var title = '其他';
        var children = [];
        for (let index = 0; index < liEles.length; index++) {
            const liEle = $(liEles[index]);
            if (liEle.hasClass('text')) {
                title = liEle.text().trim();
                continue;
            }
            const aEle = liEle.find('a');
            var href = aEle.attr('href');
            if (!href) href = '';
            children.push({
                href,
                title: aEle.text().trim(),
                hrefType: "videoList",
                active: liEle.hasClass('conch-01'),
            });
        }
        menu.push({ title, children });
    }
    const list = [];
    const liEles = $('ul.vodlist li.vodlist_item');
    for (let index = 0; index < liEles.length; index++) {
        const liEle = $(liEles[index]);
        const a = liEle.find('a');
        const href = a.attr('href');
        const imagePath = a.attr('data-original');
        const hint = a.text().trim();
        const synopsis = liEle.find('p.vodlist_sub').text().trim();
        const title = a.attr('title');
        list.push({ title, href, hrefType: 'videoInfo', playHref: loadPlayHref(a.attribs['href']), hint, imagePath, synopsis, });
    }
    return { menu, children: list, page: parsePage($) };
}
function parsePage($) {
    const pageEle = $('div.page_tips')
    if (pageEle && pageEle.length > 0) {
        const content = pageEle.text().trim().replace(/\s+/g, '');
        const found = content.match(/[0-9]+/g);
        const page = parseInt(found[0]);
        const pageSize = parseInt(found[1]);
        const hrefAEles = $('ul.page li a');
        const lastHref = decodeURI(hrefAEles[1].attribs['href']);
        const nextHref = decodeURI(hrefAEles[hrefAEles.length - 2].attribs['href']);
        const endHref = decodeURI(hrefAEles[hrefAEles.length - 1].attribs['href']);
        return { page, pageSize, lastHref, nextHref, endHref };
    }
    return undefined;
}

function searchVideo(content) {
    const $ = cheerio.load(content);
    const liEles = $('ul.vodlist li.searchlist_item');
    const children = [];
    for (let index = 0; index < liEles.length; index++) {
        const liEle = $(liEles[index]);
        const a = liEle.find('a.vodlist_thumb');
        const title = a.attr('title');
        const href = a.attr('href');
        const imagePath = a.attr('data-original');
        const hint = liEle.find('span.pic_text').text().trim();
        const pEles = liEle.find('p.vodlist_sub');
        const actor = $(pEles[0]).text().trim() +'；'+ $(pEles[1]).text().trim();
        const score = $(pEles[2]).text().trim();
        children.push({ title, href, hrefType: 'videoInfo', playHref: loadPlayHref(href), hint, score, actor, imagePath });
    }
    return { title: "搜索", children, page: parsePage($) };
}

function loadVideoPath(content) {
    const $ = cheerio.load(content);
    const script = $('script').filter((_, value) => $(value).text().indexOf('main') > -1);
    var item = script.text().trim();
    var index = item.indexOf('$');
    if (index > -1) {
        item = item.substring(0, index);
    }
    // console.log(item);
    eval(item);
    return main;
}


async function videoPlayPath(content, tag) {
    // return await require('./bmdyy').videoPlayPath(content, 'acgrw');
    var infoList = loadPreVideoPath(content);
    const preVideoPath = infoList.url;
    if (preVideoPath.endsWith('.m3u8')) {
        return { list: infoList.list, videoPath: { url: preVideoPath }, synopsis: infoList.synopsis, title: infoList.vod_name, nowPart: infoList.vod_part };
    }
    var q = url.parse(preVideoPath, true);
    var newHost = q.protocol + "//" + q.host + "";
    try {
        const newContent = await loadContent(preVideoPath, tag, 'videoPlayPath');
        var videoPath = newHost + loadVideoPath(newContent);
        return { list: infoList.list, videoPath: { url: videoPath }, synopsis: infoList.synopsis, title: infoList.vod_name, nowPart: infoList.vod_part };
    } catch (error) {
        // console.log(error);
        return { list: infoList.list, videoPath: { error: `${error}` }, synopsis: infoList.synopsis, title: infoList.vod_name, nowPart: infoList.vod_part };
    }
}
function loadPreVideoPath(content) {
    const $ = cheerio.load(content);
    const synopsis = $('div.play_content.panel').text().trim().replace(/\n\s+/g, '；');
    const list = [];
    const divEles = $('div.play_list_box');
    for (let index = 0; index < divEles.length; index++) {
        const divEle = $(divEles[index]);
        const title = divEle.find('div.player_infotip').text().trim().replace(/\n/g, ' ').split(' ')[1];
        const liEles = divEle.find('ul.content_playlist.list_scroll li');
        const items = [];
        for (let index = 0; index < liEles.length; index++) {
            const liEle = liEles[index];
            const className = liEle.attribs['class'];
            const aEle = $(liEle).find('a')[0];
            const href = aEle.attribs['href'];
            items.push({ active: className ? true : false, href, hrefType: 'videoPlayPath', title: aEle.children[0].data });
        }
        var bean = {};
        bean[title] = items;
        list.push(bean);
    }
    var script = $('script').filter((_, value) => $(value).text().indexOf('player_data') > -1);
    var htmlText = script.text().trim();
    eval(htmlText);
    var aaaa = player_data;
    aaaa.vod_name = $('div.play_vlist_text.vnow div p')[0].children[0].data;
    aaaa.vod_part = $('div.play_vlist_text.vnow p.play_vlist_now').text();
    aaaa.list = list;
    aaaa.synopsis = synopsis;
    return aaaa;
}
module.exports = { homepage, videoList,searchVideo,videoPlayPath  };